package com.ldzn.lll.mygulimall.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldzn.lll.mygulimall.common.utils.PageUtils;
import com.ldzn.lll.mygulimall.common.utils.Query;

import com.ldzn.lll.mygulimall.product.dao.CategoryDao;
import com.ldzn.lll.mygulimall.product.entity.CategoryEntity;
import com.ldzn.lll.mygulimall.product.service.CategoryService;


/**
 * @author liulianglin
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类信息
        List<CategoryEntity> resultList = baseMapper.selectList(null);
        //2.组装父子树状结构
        //查找一级分类，父分类ID为0
        List<CategoryEntity> parentList =  resultList.stream().filter((categoryEntity)->
            categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildren(menu, resultList));
            return menu;
        }).sorted(Comparator.comparing(CategoryEntity::getSort, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());


        return parentList;
    }

    /**
     删除分类菜单
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单是否被别的地方引用

        // 逻辑删除 show_status为0表示不显示
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> getChildren(CategoryEntity root,
                                             List<CategoryEntity> categoryEntityList){
        List<CategoryEntity> childList = categoryEntityList.stream().filter(categoryEntity -> {
           return categoryEntity.getParentCid() == root.getCatId();
        }).map((categoryEntity)->{
            categoryEntity.setChildren(getChildren(categoryEntity, categoryEntityList));
            return categoryEntity;
        }).sorted(Comparator.comparing(CategoryEntity::getSort, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return childList;
    }

}
